/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server;

import Common.IBackupServer;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Mario,Thomas,Max,Martin,Sergio
 */
public class MainServer
{

    private final static String SPREAD_GROUP_NAME = "alcatraz";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        Registry _registry = null;
        String hostName = "localhost"; //Default Value
        String privateGroupName = "server" + String.valueOf(new Random().nextInt(10));    //Default Value for InstanceName
//        Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
//        privateGroupName = currentTimestamp.toString();
        if (args.length > 0)
        {
            hostName = args[0];  //HostName defines the Name of the Server for connect to the spread Group
        }
        if (args.length > 1)
        {
            privateGroupName = args[1];  //Private GroupName for spread
        }

        try
        {
            _registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
        }
        catch (RemoteException ex)
        {
            System.out.println("Registry läuft bereits, Neustart?!?!?!?" + ex.getMessage());
            try
            {
                _registry = LocateRegistry.getRegistry(Registry.REGISTRY_PORT);
            }
            catch (RemoteException ex1)
            {
                Logger.getLogger(MainServer.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
        try
        {
            System.out.println("Starting up server...");
            IBackupServer s = new GameServerImpl(hostName, 0, privateGroupName);   //Mit Port 0 nimmt er den standard Port, for Future Use

            Boolean rObjAlreadyRegistered = false;
            String[] names = _registry.list();
            for (String nam : names)
            {
                if (nam.contains("AlcatrazServer"))
                {
//                    System.out.println("Auf diesem Rechner läuft bereits ein Alcatraz Server.");
//                    throw new Exception("Auf diesem Rechner läuft bereits ein Alcatraz Server.");
                    rObjAlreadyRegistered = true;
                }
            }
            if (rObjAlreadyRegistered)
            {
                //Dient nur fürs testen, damit ich zwei Server registrieren kann und diese debuggen kann
                Naming.rebind("rmi://localhost:" + String.valueOf(Registry.REGISTRY_PORT) + "/AlcatrazServerBackup", (Remote) s);  //Nur für Testzwecke
                System.out.println("Server an neuen Namen gebunden::AlcatrazServerBackup");
            }
            else
            {
                Naming.rebind("rmi://localhost:" + String.valueOf(Registry.REGISTRY_PORT) + "/AlcatrazServer", (Remote) s);  //Man kann sich nur an die lokale Registry hängen
            }
            System.out.println("server registered and running.");

            if (s.JoinGroup(SPREAD_GROUP_NAME))
            {
                s.Idle();   //Laufen lassen
            }
            else
            {
                throw new Exception("Fehler bei Spread Verbindung!");
            }
        }
        catch (Exception e)
        {
            try
            {
                Naming.unbind("rmi://localhost:" + String.valueOf(Registry.REGISTRY_PORT) + "/AlcatrazServer"); //Wenn etwas schiefgegangen ist, nehmen wir es wieder weg
            }
            catch (RemoteException ex)
            {
                Logger.getLogger(MainServer.class.getName()).log(Level.SEVERE, null, ex);
            }
            catch (NotBoundException ex)
            {
                Logger.getLogger(MainServer.class.getName()).log(Level.SEVERE, null, ex);
            }
            catch (MalformedURLException ex)
            {
                Logger.getLogger(MainServer.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("Trouble!");
            e.printStackTrace();
        }
    }
}

